using Dapper;
using Finance.Api.Read.Applications.Commands.库存盘点;
using Finance.Api.Read.Dtos;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Text;
using System.Linq;

namespace Finance.Api.Read.Applications.CommandHands.库存盘点
{
    public class DetailQueryCommandHandlers : IRequestHandler<DetailQueryCommand, ApiResult<List<DetailDto>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<DetailQueryCommandHandlers> _logger;

        public DetailQueryCommandHandlers(IDapperDb db, ILogger<DetailQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<List<DetailDto>>> Handle(DetailQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<DetailDto>>();
            StringBuilder stringBuilder = new StringBuilder();

            var parameters = new DynamicParameters();
            try
            {
                stringBuilder.Append(@"SELECT a.Id,
                            a.checkid,
                            a.ProductNo,
                            a.ProductName,
                            a.ProductNum,
                            a.Location,
                            a.ProductNumNow,
                            a.DiffNum,
                            a.Detailstatu,
                            a.CreateName,
                            a.CreateTime,
                            a.UpdateName,
                            a.UpdateTime,
                            a.DeleteName,
                            a.DeleteTime
                    FROM `Detail` a
                    WHERE 1=1
                            AND a.IsDelete=0 
                            AND a.checkid = @checkid ");

                // 添加盘点表主键ID参数
                parameters.Add("checkid", request.checkid);

                // 添加排序
                stringBuilder.Append(" ORDER BY a.Id DESC");

                // 记录SQL语句用于调试
                var sql = stringBuilder.ToString();
                _logger.LogInformation("盘点明细查询SQL: {SQL}, checkid: {CheckId}", sql, request.checkid);

                // 执行数据查询
                var list = await _db.Query<DetailDto>(sql, parameters);
                
                result.data = list.ToList();
                result.message = $"盘点明细查询成功，找到 {result.data.Count} 条记录";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("盘点明细查询失败: {Message}", ex.Message);
                result.message = "盘点明细查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 